"""
数据库模型定义
"""
from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, Boolean, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime
from config.config import settings

Base = declarative_base()

class ObjectMetadata(Base):
    """对象元数据表"""
    __tablename__ = "object_metadata"
    
    id = Column(Integer, primary_key=True, index=True)
    object_name = Column(String(255), nullable=False, comment="对象名称")
    schema_data = Column(Text, nullable=False, comment="JSON Schema数据")
    created_at = Column(DateTime, default=datetime.utcnow, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment="更新时间")
    
    # 关系
    fields = relationship("ObjectField", back_populates="obj_metadata")
    test_cases = relationship("TestCase", back_populates="obj_metadata")

class ObjectField(Base):
    """对象字段表"""
    __tablename__ = "object_fields"
    
    id = Column(Integer, primary_key=True, index=True)
    metadata_id = Column(Integer, ForeignKey("object_metadata.id"), nullable=False)
    field_name = Column(String(255), nullable=False, comment="字段名称")
    field_type = Column(String(100), nullable=False, comment="字段类型")
    is_required = Column(Boolean, default=False, comment="是否必填")
    constraints = Column(Text, comment="约束条件(JSON格式)")
    description = Column(Text, comment="字段描述")
    created_at = Column(DateTime, default=datetime.utcnow)
    
    # 关系
    obj_metadata = relationship("ObjectMetadata", back_populates="fields")

class TestCase(Base):
    """测试用例表"""
    __tablename__ = "test_cases"
    
    id = Column(Integer, primary_key=True, index=True)
    metadata_id = Column(Integer, ForeignKey("object_metadata.id"), nullable=False)
    case_name = Column(String(255), nullable=False, comment="测试用例名称")
    case_type = Column(String(50), nullable=False, comment="测试类型(create/update/delete/query)")
    scenario = Column(String(100), nullable=False, comment="测试场景(normal/boundary/exception)")
    description = Column(Text, comment="测试用例描述")
    test_data = Column(Text, comment="测试数据(JSON格式)")
    expected_result = Column(Text, comment="预期结果")
    ai_prompt = Column(Text, comment="AI生成提示词")
    created_at = Column(DateTime, default=datetime.utcnow)
    
    # 关系
    obj_metadata = relationship("ObjectMetadata", back_populates="test_cases")
    executions = relationship("TestExecution", back_populates="test_case")

class TestExecution(Base):
    """测试执行记录表"""
    __tablename__ = "test_executions"
    
    id = Column(Integer, primary_key=True, index=True)
    test_case_id = Column(Integer, ForeignKey("test_cases.id"), nullable=False)
    execution_time = Column(DateTime, default=datetime.utcnow, comment="执行时间")
    status = Column(String(50), nullable=False, comment="执行状态(success/failed/error)")
    request_data = Column(Text, comment="请求数据")
    response_data = Column(Text, comment="响应数据")
    error_message = Column(Text, comment="错误信息")
    duration = Column(Integer, comment="执行时长(毫秒)")
    
    # 关系
    test_case = relationship("TestCase", back_populates="executions")

class GlobalVariable(Base):
    """全局变量表"""
    __tablename__ = "global_variables"
    
    id = Column(Integer, primary_key=True, index=True)
    var_name = Column(String(255), nullable=False, unique=True, comment="变量名")
    var_value = Column(Text, comment="变量值")
    var_type = Column(String(50), default="string", comment="变量类型")
    description = Column(Text, comment="变量描述")
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

# 数据库引擎和会话
engine = create_engine(settings.database_url, echo=False)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def create_tables():
    """创建数据库表"""
    Base.metadata.create_all(bind=engine)

def get_db():
    """获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close() 